package com.uduemc.security.controller.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.uduemc.security.core.filter.ValidateCodeFilter;

@Component
public class TimeInterceptor implements HandlerInterceptor {
	
	@Autowired
	private ValidateCodeFilter customValidateCodeFilter;

	/**
	 * 在控制器方法被调用之前调用 返回 false 则不在往下执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println(" Interceptor: preHandle");
		System.out.println(" Interceptor: customValidateCodeFilter: " + customValidateCodeFilter);
		
		// 控制器的类名
		String handleClassName = ((HandlerMethod) handler).getBean().getClass().getName();
		// 控制器执行的方法名
		String handleMethodName = ((HandlerMethod) handler).getMethod().getName();
		request.setAttribute("startTime", (new Date()).getTime());
		System.out.println("  handleClassName: " + handleClassName);
		System.out.println("  handleMethodName: " + handleMethodName);
		return true;
	}

	/**
	 * 在控制方法调用成功后调用
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println(" Interceptor: postHandle runtime: "
				+ (new Date().getTime() - (long) request.getAttribute("startTime")));
	}

	/**
	 * 无论控制器的方式调用成功还是失败都会调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println(" Interceptor: afterCompletion runtime: "
				+ (new Date().getTime() - (long) request.getAttribute("startTime")));
	}

}
